// VideoPlayer 组件的业务逻辑函数

export { render } from './html.js';

/**
 * 绑定事件监听器
 * @param {VideoPlayer} component - 组件实例
 */
export function bindEvents(component) {
    const videoElement = component.shadowRoot.querySelector('.video-element');
    const playPauseBtn = component.shadowRoot.querySelector('.play-pause-btn');
    const videoContainer = component.shadowRoot.querySelector('.video-container');
    const videoOverlay = component.shadowRoot.querySelector('.video-overlay');
    const indicators = component.shadowRoot.querySelectorAll('.indicator');
    
    // 初始化控制按钮隐藏超时
    component.controlsTimeout = null;
    
    // 播放/暂停控制
    playPauseBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        togglePlayPause(component);
        hideControlsAfterDelay(component);
    });
    
    // 点击视频区域显示控制按钮并切换播放状态
    videoContainer.addEventListener('click', (e) => {
        if (e.target !== playPauseBtn && !playPauseBtn.contains(e.target)) {
            showControls(component);
            togglePlayPause(component);
            hideControlsAfterDelay(component);
        }
    });
    
    // 滚轮事件
    component.addEventListener('wheel', (e) => {
        handleWheel(component, e);
    }, { passive: false });
    
    // 键盘事件
    component.addEventListener('keydown', (e) => {
        handleKeydown(component, e);
    });
    
    // 指示器点击事件
    indicators.forEach(indicator => {
        indicator.addEventListener('click', () => {
            const index = parseInt(indicator.dataset.index);
            goToVideo(component, index);
        });
    });
    
    // 视频进度更新
    videoElement.addEventListener('timeupdate', () => {
        updateProgress(component);
    });
    
    // 视频加载完成
    videoElement.addEventListener('loadedmetadata', () => {
        updateProgress(component);
    });
    
    // 视频播放状态变化
    videoElement.addEventListener('play', () => {
        const videoOverlay = component.shadowRoot.querySelector('.video-overlay');
        videoOverlay.classList.add('playing');
    });
    
    videoElement.addEventListener('pause', () => {
        const videoOverlay = component.shadowRoot.querySelector('.video-overlay');
        videoOverlay.classList.remove('playing');
    });
}

/**
 * 处理滚轮事件
 * @param {VideoPlayer} component - 组件实例
 * @param {WheelEvent} e - 滚轮事件
 */
export function handleWheel(component, e) {
    e.preventDefault();
    
    if (component.isScrolling) return;
    
    component.isScrolling = true;
    
    if (e.deltaY > 0) {
        nextVideo(component);
    } else {
        prevVideo(component);
    }
    
    clearTimeout(component.scrollTimeout);
    component.scrollTimeout = setTimeout(() => {
        component.isScrolling = false;
    }, 500);
}

/**
 * 处理键盘事件
 * @param {VideoPlayer} component - 组件实例
 * @param {KeyboardEvent} e - 键盘事件
 */
export function handleKeydown(component, e) {
    switch(e.key) {
        case ' ':
        case 'Enter':
            e.preventDefault();
            togglePlayPause(component);
            break;
        case 'ArrowUp':
            e.preventDefault();
            prevVideo(component);
            break;
        case 'ArrowDown':
            e.preventDefault();
            nextVideo(component);
            break;
    }
}

/**
 * 切换播放/暂停状态
 * @param {VideoPlayer} component - 组件实例
 */
export function togglePlayPause(component) {
    const videoElement = component.shadowRoot.querySelector('.video-element');
    
    if (videoElement.paused) {
        videoElement.play().catch(console.error);
    } else {
        videoElement.pause();
    }
}

/**
 * 播放下一个视频
 * @param {VideoPlayer} component - 组件实例
 */
export function nextVideo(component) {
    if (component.currentIndex < component.videos.length - 1) {
        component.currentIndex++;
        loadCurrentVideo(component);
        animateTransition(component, 'down');
    }
}

/**
 * 播放上一个视频
 * @param {VideoPlayer} component - 组件实例
 */
export function prevVideo(component) {
    if (component.currentIndex > 0) {
        component.currentIndex--;
        loadCurrentVideo(component);
        animateTransition(component, 'up');
    }
}

/**
 * 跳转到指定视频
 * @param {VideoPlayer} component - 组件实例
 * @param {number} index - 视频索引
 */
export function goToVideo(component, index) {
    if (index >= 0 && index < component.videos.length && index !== component.currentIndex) {
        const direction = index > component.currentIndex ? 'down' : 'up';
        component.currentIndex = index;
        loadCurrentVideo(component);
        animateTransition(component, direction);
    }
}

/**
 * 加载当前视频
 * @param {VideoPlayer} component - 组件实例
 */
export function loadCurrentVideo(component) {
    const videoElement = component.shadowRoot.querySelector('.video-element');
    
    const currentVideo = component.videos[component.currentIndex];
    
    if (currentVideo) {
        videoElement.src = currentVideo.src;
        videoElement.poster = currentVideo.poster;
        
        // 重置进度条
        updateProgress(component);
        
        // 更新指示器
        updateIndicators(component);
        
        // 触发视频切换事件，通知其他组件
        component.dispatchEvent(new CustomEvent('video-changed', {
            detail: {
                video: currentVideo,
                index: component.currentIndex,
                total: component.videos.length
            }
        }));
        
        // 加载视频并自动播放
        videoElement.load();
        
        // 确保视频自动播放
        videoElement.play().catch(console.error);
    }
}

/**
 * 更新指示器状态
 * @param {VideoPlayer} component - 组件实例
 */
export function updateIndicators(component) {
    const indicators = component.shadowRoot.querySelectorAll('.indicator');
    indicators.forEach((indicator, index) => {
        indicator.classList.toggle('active', index === component.currentIndex);
    });
}

/**
 * 更新进度条
 * @param {VideoPlayer} component - 组件实例
 */
export function updateProgress(component) {
    const videoElement = component.shadowRoot.querySelector('.video-element');
    const progressFill = component.shadowRoot.querySelector('.progress-fill');
    
    if (videoElement.duration) {
        const progress = (videoElement.currentTime / videoElement.duration) * 100;
        progressFill.style.width = `${progress}%`;
    }
}

/**
 * 播放切换动画
 * @param {VideoPlayer} component - 组件实例
 * @param {string} direction - 动画方向 ('up' 或 'down')
 */
export function animateTransition(component, direction) {
    const videoContainer = component.shadowRoot.querySelector('.video-container');
    
    videoContainer.style.transform = direction === 'down' ? 'translateY(-20px)' : 'translateY(20px)';
    videoContainer.style.opacity = '0.8';
    
    setTimeout(() => {
        videoContainer.style.transform = 'translateY(0)';
        videoContainer.style.opacity = '1';
    }, 150);
}

/**
 * 播放视频
 * @param {VideoPlayer} component - 组件实例
 */
export function play(component) {
    const videoElement = component.shadowRoot.querySelector('.video-element');
    return videoElement.play();
}

/**
 * 暂停视频
 * @param {VideoPlayer} component - 组件实例
 */
export function pause(component) {
    const videoElement = component.shadowRoot.querySelector('.video-element');
    videoElement.pause();
}

/**
 * 显示控制按钮
 * @param {VideoPlayer} component - 组件实例
 */
export function showControls(component) {
    const videoOverlay = component.shadowRoot.querySelector('.video-overlay');
    videoOverlay.classList.add('show-controls');
}

/**
 * 隐藏控制按钮
 * @param {VideoPlayer} component - 组件实例
 */
export function hideControls(component) {
    const videoOverlay = component.shadowRoot.querySelector('.video-overlay');
    videoOverlay.classList.remove('show-controls');
}

/**
 * 延迟隐藏控制按钮
 * @param {VideoPlayer} component - 组件实例
 * @param {number} delay - 延迟时间（毫秒），默认3000ms
 */
export function hideControlsAfterDelay(component, delay = 3000) {
    // 清除之前的超时
    if (component.controlsTimeout) {
        clearTimeout(component.controlsTimeout);
    }
    
    // 设置新的超时
    component.controlsTimeout = setTimeout(() => {
        hideControls(component);
    }, delay);
}